<template>
  <div class="common-layout">
    <el-form class="header" :model="queryParam" ref="queryRef" :inline="true">
      <el-form-item label="名称" prop="name">
        <el-input
            style="width: 200px"
            v-model="queryParam.name"
            placeholder="请输入任务名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="校区" prop="name">
        <el-tree-select
            style="width: 200px"
            v-model="queryParam.dept"
            :data="enabledDeptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="选择校区"
            check-strictly/>
      </el-form-item>

      <el-form-item label="状态" prop="active">
        <el-select v-model="queryParam.active" placeholder="请选择任务状态" clearable style="width: 200px">
          <el-option
              v-for="dict in task_active_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <!--        <el-button icon="Refresh" >{{message}}</el-button>-->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="margin-left: 5px;margin-bottom: 10px">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            @click="handleAdd"
        >新增(通用)
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            @click="handleWord"
        >新增(高中单词)
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            @click="handleSenior"
        >新增(核心872)
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            @click="handlePrimary"
        >新增(初中单词)
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            :disabled="single"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            :disabled="single"
            @click="handleCopyAll(null)"
        >复制
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            :disabled="single"
            @click="handleCopyAll('')"
        >复制(月底)
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            :disabled="single"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>

      <el-col :span="1.5" style="margin-left: auto;margin-right: 15px">
        <el-button
            type="primary"
            plain
            @click="mySentTask(null)"
        >我的分配
        </el-button>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-right: 5px">
      <el-col :sm="24" :lg="24" style="padding-left: 20px;">
        <el-table border :data="stepList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="任务编号" width="80" align="center" prop="id"/>
          <el-table-column label="任务名称" align="center" prop="name"/>
          <el-table-column label="校区" width="80" align="center" prop="campus"/>

          <el-table-column label="已分配的学生" min-width="200" align="center" prop="studentName">
          </el-table-column>

          <el-table-column label="任务截止时间" width="180" align="center" prop="scope">
          </el-table-column>

          <el-table-column label="最低比率" width="80" align="center" prop="rate">
            <template #default="scope">
              <span v-if="scope.row.type !== '2' && scope.row.type !== '3' ">---</span>
              <span v-else-if="scope.row.rate === null">未填写</span>
              <span v-else>{{scope.row.rate}}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建人" width="80" align="center" prop="people"/>
          <el-table-column label="创建时间"  width="180" align="center" prop="time">
            <template #default="scope">
              <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>

          <el-table-column width="80" label="状态" align="center" prop="active">
            <template #default="scope">
              <dict-tag :options="task_active_status" :value="scope.row.active"/>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
            <template #default="scope">
              <div>
                <el-button
                    v-if="scope.row.active === 3"
                    link
                    type="success"
                    @click="handleAddStudent(scope.row)"
                >分配学生
                </el-button>
                <span v-if="scope.row.active !== 3">已分配</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            style="margin-right: 20px"
            v-show="size > 0"
            :total="size"
            v-model:page="queryParam.pageNum"
            v-model:limit="queryParam.pageSize"
            @pagination="handleQuery"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改任务   -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="dictRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称"/>
        </el-form-item>
        <el-form-item v-if="false" label="总步数" prop="total">
          <el-input-number style="width: 100%" v-model="form.total" placeholder="请输入总步数"/>
        </el-form-item>

        <el-form-item label="限时" prop="scope">
          <el-date-picker
              @change="dateDetailChange"
              style="width: 100%"
              v-model="form.scope"
              type="date"
              placeholder="请选择截止时间"
          />
        </el-form-item>

        <el-form-item label="校区" prop="campus">
          <el-tree-select
              style="width: 100%"
              @change="selectChange"
              v-model="form.campus"
              :data="enabledDeptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
              placeholder="校区" check-strictly/>
        </el-form-item>

        <el-form-item v-if="open_word" label="书名" prop="ipaddr">
          <el-select style="width: 100%" clearable v-model="form.book" placeholder="请选择书名">
            <el-option v-for="item in 7" :key="item" :label="`${('book')}${item}`" :value="`${('book')}${item}`"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="open_word" label="单元" prop="ipaddr">
          <el-select style="width: 100%" clearable v-model="form.unit" placeholder="请选择单元">
            <el-option v-for="item in 6" :key="item" :label="`${('unit')}${item}`" :value="`${('unit')}${item}`"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="open_word" label="类型" prop="ipaddr">
          <el-select style="width: 100%" clearable v-model="form.type" placeholder="请选择类型">
            <el-option v-for="item in typeStatus" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.type === 2" label="完成率" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入至少完成的比例(0-1)"/>
        </el-form-item>

        <el-form-item v-if="form.type === 3"  label="正确率" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入测试结果至少的比例(0-1)"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="核心872任务" v-model="senior_open" width="700px" append-to-body>
      <el-form ref="dictRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称(组号自动添加到最后)"/>
        </el-form-item>

        <el-form-item label="截止日期" prop="scope">
          <el-date-picker
              @change="dateDetailChange"
              style="width: 100%"
              v-model="form.scope"
              type="date"
              placeholder="请选择截止日期"
          />
        </el-form-item>

        <el-form-item label="校区" prop="campus">
          <el-tree-select
              style="width: 100%"
              @change="selectChange"
              v-model="form.campus"
              :data="enabledDeptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
              placeholder="校区" check-strictly/>
        </el-form-item>

        <el-form-item label="组号" prop="group">
          <el-input clearable v-model="groupNum"
                    style="width: 100%"
                    @blur="inputKeyUpEvent"
                    placeholder="请输入组号(1-18)"></el-input>
        </el-form-item>

        <el-form-item label="类型" prop="ipaddr">
          <el-select style="width: 100%" clearable v-model="form.type" placeholder="请选择类型">
            <el-option v-for="item in typeStatus" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.type === 2" label="完成率" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入至少完成的比例(0-1)"/>
        </el-form-item>

        <el-form-item v-if="form.type === 3"  label="正确率" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入测试结果至少的比例(0-1)"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="初中单词任务" v-model="primary_open" width="700px" append-to-body>
      <el-form ref="dictRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称"/>
        </el-form-item>

        <el-form-item label="单词内容" prop="ipaddr">
          <el-cascader
              style="width: 100%"
              filterable clearable v-model="form.text"
              @change="handleChange"
              :options="bookAndUnitList">
            <template #default="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>

        <el-form-item label="截止日期" prop="scope">
          <el-date-picker
              @change="dateDetailChange"
              style="width: 100%"
              v-model="form.scope"
              type="date"
              placeholder="请选择截止日期"
          />
        </el-form-item>

        <el-form-item label="校区" prop="campus">
          <el-tree-select
              style="width: 100%"
              @change="selectChange"
              v-model="form.campus"
              :data="enabledDeptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
              placeholder="校区" check-strictly/>
        </el-form-item>

        <el-form-item label="类型" prop="ipaddr">
          <el-select style="width: 100%" clearable v-model="form.type" placeholder="请选择类型">
            <el-option v-for="item in typeStatus" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.type === 2" label="完成率" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入至少完成的比例(0-1)"/>
        </el-form-item>

        <el-form-item v-if="form.type === 3"  label="正确率" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入测试结果至少的比例(0-1)"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="添加学生" v-model="addStudent" width="500px" height="500px" append-to-body>
      <el-form ref="formDetail" :model="formStudent" label-width="60px">

        <el-form-item label="学生" prop="student">
          <el-select @change="selectChange_multiple" placeholder="选择指定校区中的学生"
                     filterable multiple clearable style="width: 100%" v-model="formStudent.studentId">
            <el-option
                v-for="item in studentsList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addStudent = false">取消</el-button>
          <el-button type="primary" @click="addStudentSubmit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<!--简化版-正在使用-->
<script setup>
import {ref} from "vue";
import {
  addStep, addStep_progress,
  addTask_detail,
  updateTask_detail,
  addTaskAddstudent,
  delStep,
  delTaskAddstudent,
  getStep,
  listStep,
  updateStep,
  typeStatus
} from "@/api/teach/step.js";
import {parseTime} from "@/utils/ruoyi.js";
import {getUserList} from "@/api/system/user.js";
import {deptTreeSelect} from "@/api/system/user"
import {mySentTask} from '@/api/teach/route.js'
import {isNumberStr} from "@/utils/index.js";
import {bookAndUnitList} from "@/api/primary/index.js";

// 日期时间格式（显示用）
const dateTimeFormat = 'YYYY-MM-DD HH:59:59';
const {proxy} = getCurrentInstance()

let queryParam = ref({
  pageNum: 1,
  pageSize: 10
})

const ids = ref([])
const single = ref(true)
const multiple = ref(true)
let size = ref(0)
const {task_active_status} = proxy.useDict("task_active_status")
const enabledDeptOptions = ref(undefined)
const active = ref(0)
let stepList = ref([])
let studentsList = ref([])
let task_detailList = ref([])
let title = ref('')
let titleDetail = ref('')
let form = ref({})
let form2 = ref({})
let formStudent = ref({})
let rowRecord = ref({})
let formDetail = ref({})
let addStudentFrom = ref({})
let open = ref(false)
let open_word = ref(false)
let senior_open = ref(false)
let primary_open = ref(false)
let addStudent = ref(false)
let rules = ref({})
let groupNum = ref()

// 获取本月最后一天
const lastDayOfMonth = new Date(
    new Date().getFullYear(),             // 当前年份
    new Date().getMonth() + 1,  // 下个月（当前月份 + 1）
    0                                 // 日期设为 0，会自动转换为上个月的最后一天
);

initPage()

function initPage() {
  handleQuery()
  getDeptTree()
}

//查询学生列表
function getUserListByDept(dept) {
  getUserList(200, dept).then(res => {
    studentsList.value = res.data
    // console.log(res)
  })
}

function handleChange(val){
  // console.log(val)
  form.value.book = val[0]
  form.value.unit = val[1]
}

//时间事件-详情
function dateDetailChange(date) {
  form.value.scope = parseTime(date, '{y}-{m}-{d} 23:59:59')
  // console.log(form.value)
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

//校区改变事件
function selectChange(val) {
  form.value.dept = val
  form.value.campus = findLabelById(enabledDeptOptions.value, val);
}

/**
 * 通过ID 查找 el-tree-select中data的label
 * */
function findLabelById(data, id) {
  for (let i = 0; i < data.length; i++) {
    if (data[i].id === id) {
      return data[i].label;
    }
    if (data[i].children && data[i].children.length > 0) {
      const result = findLabelById(data[i].children, id);
      if (result) return result;
    }
  }
  return null; // 如果没有找到对应id的label，则返回null
}

/**
 * 添加学生数据提交
 * */
function addStudentSubmit() {
  let studentForm = {
    id:rowRecord.value.id,
    active: 2,
    complete:rowRecord.value.complete,
    studentId:rowRecord.value.studentId,
    studentName:rowRecord.value.studentName,
  }
  updateStep(studentForm).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("分配学生成功");
      addStudent.value = false
      handleQuery()
    }
  })
  startTaskNewTable(rowRecord.value)
}

function selectChange_multiple(val) {
  // console.log(val)
  // console.log(val.length)
  let nameArray = []
  for (const [index, items] of val.entries()) {
    // console.log(`索引 ${index}：${item}`);
    let number = studentsList.value.findIndex(item => {
      return item.userId === items
    });
    let name = studentsList.value[number]['userName'];
    nameArray.push(name)
  }
  rowRecord.value.complete = val.length
  rowRecord.value.studentId = val.toString()
  rowRecord.value.studentName = nameArray.join(",")
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    // deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

function submitForm() {
  // console.log(form.value)
  if (form.value.id !== undefined && form.value.id !== null) {
    updateStep(form.value).then(response => {
      proxy.$modal.msgSuccess("任务修改成功");
      handleQuery()
    })
  } else {
    form.value.total = 1
    if (form.value.times !== undefined && form.value.times !== null &&
        form.value.times !== 0 && form.value.name.indexOf('组号') === -1) {
      form.value.name = form.value.name +  "-组号:" + form.value.times
    }
    // console.log(form.value)
    addStep(form.value).then(response => {
      proxy.$modal.msgSuccess("新增任务成功");
      handleQuery()
    });
  }
  windowClose()
}

function handleCopyAll(date) {
  const id = ids.value
  proxy.$modal.confirm('是否确认复制编号为:' + id + '的任务？').then(function () {
    return handleCopy(date)
  }).then(() => {
    handleQuery()
    proxy.$modal.msgSuccess("复制成功")
  }).catch(() => {
    proxy.$modal.msg("取消复制")
  })
}

function handleDelete(row) {
  const id = row.id || ids.value
  getStep(id).then(response => {
    if (parseInt(response.data.active) === 2) {
      proxy.$modal.msgWarning("执行中的任务不可删除");
      return
    }
    proxy.$modal.confirm('是否确认删除"' + id + '"的数据项？').then(function () {
      return delStep(id)
    }).then(() => {
      handleQuery()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {
      proxy.$modal.msg("取消删除")
    })
  })
}

function cancel() {
  windowClose()
  proxy.$modal.msg("取消操作");
}

function windowClose(){
  open.value = false;
  open_word.value = false;
  senior_open.value = false;
  primary_open.value = false;
}

function startTaskNewTable(row) {
  console.log(row)
  let tableForm = {
    main: row.id,
    total: row.total,
    type: row.type,
    rate: row.rate,
    name: row.name,
    people: row.people,
    scope: row.scope,
    step: 1,
    end: row.scope,
    active: 3
  }
  // console.log(tableForm)
  if (row.times !== undefined && row.times !== null && row.times !== 0) {
    if (parseInt(row.type) === 2) {
      tableForm.content = "需要完成的高中核心872单词学习:组号-" + row.times
    } else if (parseInt(row.type) === 3) {
      tableForm.content = "需要完成的高中核心872单词测试:组号-" + row.times
    } else {
      tableForm.content = row.name
    }
  }
  else {
    if (parseInt(row.type) === 2) {
      tableForm.content = "需要完成的单词学习:书名-'" + row.book + "',单元-'" + row.unit + "'"
    } else if (parseInt(row.type) === 3) {
      tableForm.content = "需要完成的单词测试:书名-'" + row.book + "',单元-'" + row.unit + "'"
    } else {
      tableForm.content = row.name
    }
  }

  let idArray = row.studentId.toString().split(",");
  let nameArray = row.studentName.toString().split(",");

  // tableForm.complete = idArray.length
  // 如需索引，可结合 Array.entries()
  for (const [index, item] of idArray.entries()) {
    // console.log(`索引 ${index}：${item}`);
    tableForm.title = row.times
    tableForm.studentId = item
    tableForm.studentName = nameArray[index];
    addStep_progress(tableForm)
  }
  proxy.$modal.msgSuccess("任务已开始");
}

function resetQuery() {
  queryParam.value = {}
  initPage()
}

//添加主任务-1
function handleAdd() {
  open.value = true
  open_word.value = false
  title.value = "添加任务"
  form.value.type = 1
  form.value.id = null
  form.value.time = nu
  form.value.scope = null
}

//添加主任务-2
function handleWord() {
  open.value = true
  open_word.value = true
  form.value.type = null
  form.value.time = null
  form.value.id = null
  title.value = "添加单词任务"
}

function handleSenior() {
  senior_open.value = true
  form.value.type = null
  form.value.times = groupNum.value
  form.value.id = null
}

function handlePrimary() {
  primary_open.value = true
  form.value.type = null
  form.value.id = null
}

function handleQuery() {
  // console.log(queryParam)
  listStep(queryParam.value).then(response => {
    // console.log(response)
    size.value = response.total
    stepList.value = response.rows;
  });
}

function inputKeyUpEvent() {
  if (groupNum.value === '') {
    return
  }
  if (!isNumberStr(groupNum.value) || groupNum.value % 1 !== 0) {
    proxy.$modal.msgWarning("组号必须为整数")
    setTimeout(function () {
      groupNum.value = null
    },2000)
    return
  }
  if (groupNum.value > 18 || groupNum.value < 1) {
    proxy.$modal.msgWarning("组号必须在1-18之间")
    setTimeout(function () {
      groupNum.value = null
    },2000)
    return
  }
  form.value.times = groupNum.value
}

function handleUpdate(row) {
  title.value = "修改任务"
  const id = row.id || ids.value
  // console.log(id)
  getStep(id).then(response => {
    // console.log(response.data)
    if (parseInt(response.data.active) === 2) {
      proxy.$modal.msgWarning("执行中的任务不可修改");
      return
    }
    if (parseInt(response.data.active) === 1) {
      proxy.$modal.msgWarning("已完成任务不可修改");
      return
    }
    form.value = response.data
    // console.log(form.value)
    open_word.value = form.value.type === "2" || form.value.type === '3';
    form.value.type = parseInt(response.data.type)
    open.value = true
  })
}

function handleCopy(date) {
  const id = ids.value
  let form = {}
  getStep(id).then(response => {
    if (response.code === 200) {
      form = response.data
      // console.log(form)
      form.id = null
      form.studentId = null
      form.studentName = null
      if (date !== null && date !== undefined) {
        form.scope = parseTime(lastDayOfMonth, '{y}-{m}-{d} 23:59:59');
      }
      form.active = 3
      form.send = 0
      if (form.times !== undefined && form.times !== null && form.times !== 0 && form.name.indexOf('组号') === -1) {
        form.name = form.name +  "-组号:" + form.times
      }
      addStep(form).then(response => {
        if (response.code === 200) {
          // console.log(response)
          handleQuery()
        }
      })
    }
  })
}

/**
 * 添加学生
 * */
function handleAddStudent(row) {
  // console.log(row)
  if (row.campus === null || row.campus === undefined) {
    proxy.$modal.msgWarning("请先指定校区");
    return
  }
  formStudent.value.studentId = [];
  addStudent.value = true
  rowRecord.value = row
  // formStudent.value.already = row.studentList.toString().split(",")
  if (row.studentName !== null && row.studentName !== undefined) {
    formStudent.value.already = row.studentName.toString().split(",")
  } else {
    formStudent.value.already = ''
  }
  // console.log(formStudent.value.already)
  getUserListByDept(row.dept)
}

</script>

<style scoped lang="scss">
.header {
  margin-top: 20px;
  margin-left: 20px;
}

.my-dialog {
  position: absolute;
  top: 10%; /* 根据实际情况调整 */
  left: 50%;
  transform: translateX(-50%);
}

.button-container {
  display: flex;
  justify-content: space-around; /* 按钮均匀分布 */
  /* 或者使用 'space-between' 让第一个按钮靠左，最后一个按钮靠右 */
}
</style>
